package com.umakr.ax.xf;

import com.umakr.ax.utils.Mp3ConverterUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 *
 * @author gx
 * @date 2018/2/9
 */
public class Mp3ConvertorAndXfTransformService {
    protected final Log logger = LogFactory.getLog(this.getClass());
    @Autowired
    Environment env;

    private ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1000,1500,15, TimeUnit.MINUTES,new LinkedBlockingDeque<>());
    public interface MsgCall{
        /**
         * MsgCall
         * @param convertedMp3Path 转换后的Mp3路径，此路径是相对路径。
         * @param xfTransformResult 讯飞翻译结果。
         * @param errMsg 讯飞翻译结果。
         */
        void result(String convertedMp3Path,String xfTransformResult,String errMsg);
    }

    /**
     *微信语音翻译
     * @param amrMediaPath 微信amr语音路径。
     * @param rsId 电台id
     * @param userUuid 微信用户uuid
     * @param msgCall 回掉函数
     */
    public void handlerMsg(final String amrMediaPath,final Long rsId,final String userUuid,final MsgCall msgCall){
        handlerMsg(amrMediaPath,rsId,null,userUuid,msgCall);
    }
    /**
     * app 语音翻译
     * @param aacMediaPath aac语音路径。
     * @param rsId 电台id
     * @param userId 平台用户id
     * @param msgCall 回掉函数
     */
    public void handlerMsg(final String aacMediaPath,final Long rsId,final Long userId,final MsgCall msgCall){
        handlerMsg(aacMediaPath,rsId,userId,null,msgCall);
    }

    /**
     * app 和 微信实际语音翻译
     * @param mediaPath 语音路径。
     */
    private void handlerMsg(final String mediaPath,final Long rsId,final Long userId,final String userUuid,final MsgCall msgCall){
        boolean nullCondition = rsId != null && StringUtils.isNotEmpty(mediaPath) && (userId!= null || StringUtils
                .isNotEmpty(userUuid));
        if(nullCondition){
            threadPoolExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    //文件夹创建
                    String fileAbDir = "audio"+ File.separator+ rsId +File.separator + (userId == null? userUuid : userId);
                    String uploadPath = env.getProperty("media.dir") + File.separator + fileAbDir;
                    File upFileDir = new File(uploadPath);
                    if (!upFileDir.isDirectory()) {
                        upFileDir.mkdirs();
                    }

                    File file = new File(mediaPath);
                    if(file.exists()){
                        logger.info("--------mediaPath:"+file.getAbsolutePath());
                        String mp3DestPath = uploadPath + File.separator + file.getName().replace(".aac","").replace(".amr","");
                        long startConverterAACToWav = System.currentTimeMillis();
                        String resultPath = Mp3ConverterUtils.convertToWav(mediaPath);

                        logger.info("---------"+ System.getProperty("user.dir"));
                        logger.info("--------resultPath:" + resultPath);
                        logger.info("完成转换，开始翻译:" + (System.currentTimeMillis() - startConverterAACToWav));
                        RadioToWord mObject = new RadioToWord();

                        long startXf = System.currentTimeMillis();
                        String result = null;
                        try {
                            result = mObject.voice2words(resultPath);

                            long startConverterAACToMp3 = System.currentTimeMillis();
                            Mp3ConverterUtils.convertToMp3(mediaPath,mp3DestPath + ".mp3");
                            logger.info("完成转换Mp3:" + (System.currentTimeMillis() - startConverterAACToMp3));

                            String addr = fileAbDir + File.separator + file.getName().replace(".aac","").replace(".amr","")+".mp3";
                            addr = addr.replaceAll("\\\\","/");
                            msgCall.result("/" + addr,result,null);
                        } catch (InterruptedException e) {
                            logger.info(e);
                            Thread.currentThread().interrupt();
                            msgCall.result(null,null,"翻译出错。");
                        } catch (IOException e) {
                            logger.info("context",e);
                            msgCall.result(null,null,"翻译出错。");
                        }
                        logger.info("翻译结果: " +(System.currentTimeMillis() - startXf) +"  "+ result);
                    }
                }
            });
        }else{
            String msg = "";
            if (rsId == null){
                msg = "电台id为空";
            }
            if (userId != null && StringUtils.isEmpty(userUuid)){
                msg += ";用户uuid为空";
            }
            if (StringUtils.isEmpty(mediaPath)){
                msg += ";mediaPath为空";
            }
            msgCall.result(null,null,msg);
        }

    }

}
